package run.microservice.stock.aspects;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import run.microservice.stock.annotations.NotUseResponseAdvice;
import run.microservice.stock.response.Result;


/**
 * @author lunfangyu
 */
@Slf4j
@RestControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        //默认返回true
        //return true;

        //response是Result类型，或者有NotUseResponseAdvice注解都不进行统一返回包装
        return !(returnType.getParameterType().isAssignableFrom(Result.class)
                || returnType.hasMethodAnnotation(NotUseResponseAdvice.class));
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {

        // Swagger接口文档uri不做统一返回处理
        String uri = request.getURI().toString();
        String[] excludeUris = new String[]{"/doc.html", "/swagger-resources", "/api-docs", "/swagger-ui", "/webjars"};
        for (String excludeUri : excludeUris) {
            if (uri.contains(excludeUri)) {
                return body;
            }
        }

        if (body instanceof Result) {
            return body;
        }

        return Result.success(body);
    }

}
